<script lang="ts" setup>
// FluentUI components are registered in main.ts
import { computed, provide, ref, watch } from 'vue';

type RadioGroupOrientation = 'horizontal' | 'vertical';

const props = withDefaults(
  defineProps<{
    disabled?: boolean;
    modelValue?: string;
    name?: string;
    orientation?: RadioGroupOrientation;
    required?: boolean;
    value?: string;
  }>(),
  {
    disabled: false,
    name: undefined,
    orientation: 'horizontal',
    required: false,
    value: undefined,
    modelValue: undefined,
  },
);

const emit = defineEmits<{
  change: [event: Event, value: string];
  'update:modelValue': [value: string];
}>();

// Define slots
defineSlots<{
  default?: () => any;
}>();

const radioGroupRef = ref<HTMLElement | null>(null);
const internalValue = ref(props.value || props.modelValue);

// Handle modelValue prop for v-model support
const isControlled = computed(() => props.modelValue !== undefined);

watch(
  () => props.modelValue,
  (value) => {
    if (isControlled.value && value !== internalValue.value) {
      internalValue.value = value;
    }
  },
);

watch(
  () => props.value,
  (value) => {
    if (!isControlled.value && value !== internalValue.value) {
      internalValue.value = value;
    }
  },
);

// Provide radio group context to child radio components
provide('radioGroupContext', {
  name: computed(() => props.name),
  selectedValue: computed(() =>
    isControlled.value ? props.modelValue : internalValue.value,
  ),
  disabled: computed(() => props.disabled),
  updateValue: (value: string, event: Event) => {
    if (isControlled.value) {
      emit('update:modelValue', value);
    } else {
      internalValue.value = value;
    }
    emit('change', event, value);
  },
});

// Handle change event from the radio group
const handleChange = (event: Event) => {
  const target = event.target as HTMLElement;
  const value = target.getAttribute('value');

  if (value !== null) {
    if (isControlled.value) {
      emit('update:modelValue', value);
    } else {
      internalValue.value = value;
    }
    emit('change', event, value);
  }
};
</script>

<template>
  <fluent-radio-group
    ref="radioGroupRef"
    :value="isControlled ? modelValue : internalValue"
    :name="name"
    :disabled="disabled"
    :orientation="orientation"
    :required="required"
    @change="handleChange"
  >
    <slot></slot>
  </fluent-radio-group>
</template>

<style scoped></style>
